import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Space, Table, Tag, Switch, Button, message, Input, Popconfirm, Typography, Tooltip, Avatar, Modal } from 'antd';
import type { TableProps, SpinProps } from 'antd';
import { SearchOutlined, DeleteOutlined, EditOutlined, UserOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import http from '../api/http';
import { imgBaseURL } from '../api/baseURL';
import type { IUsers, IUsersWrite } from '../types/users';

import UserFormModal from './edit'

// 类型定义
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
type PaginationConfig = { current: number; pageSize: number; };

const { Column, ColumnGroup } = Table;
const { confirm } = Modal;

// 常量定义
const PAGE_SIZE_OPTIONS = ['5', '10', '20', '50', '100'];
const DEFAULT_PAGE_SIZE = 5;
const DEFAULT_CURRENT_PAGE = 1;
// 默认头像
const DEFAULT_AVATAR = 'https://picsum.photos/200';

const Users: React.FC = () => {
  // 表格选择相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<IUsers[]>([]);

  // 数据和加载状态
  const [loading, setLoading] = useState<boolean | SpinProps>({ size: 'large' });
  const [users, setUsers] = useState<Array<IUsers>>([]);
  const [totalCount, setTotalCount] = useState<number>(0);

  // 搜索和分页状态
  const [searchName, setSearchName] = useState<string>('');
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: DEFAULT_CURRENT_PAGE,
    pageSize: DEFAULT_PAGE_SIZE,
    
  });

  // 表单弹窗相关状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加用户');
  const [currentUserId, setCurrentUserId] = useState<number | null>(null);
  const [formInitialValues, setFormInitialValues] = useState<Partial<IUsers> | undefined>();

  // 处理选择变化
  const handleSelectChange = useCallback((
    newSelectedRowKeys: React.Key[],
    selectedRows: IUsers[]
  ) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedUsers(selectedRows);
  }, []);

  // 行选择配置
  const rowSelection: TableRowSelection<IUsers> = useMemo(() => ({
    selectedRowKeys,
    onChange: handleSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选择奇数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 === 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: '选择偶数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 !== 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  }), [selectedRowKeys, handleSelectChange]);

  // 获取用户数据
  const fetchUsers = useCallback(async (
    page: number = pagination.current,
    pageSize: number = pagination.pageSize,
    name?: string
  ) => {
    setLoading({ size: 'large' });
    try {
      const response = await http.getList<IUsers>('Users/list', {
        page,
        size: pageSize,
        name: name || searchName
      });
      setUsers(response.data);
      setTotalCount(response.count);
    
    } catch (error) {
      console.error('获取用户数据失败:', error);
      message.error('获取用户数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [pagination]);

  // 初始化数据和依赖变化时重新获取
  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  // 处理搜索
  const handleSearch = useCallback(() => {
    // 重置到第一页并搜索
    setPagination(prev => ({ ...prev, current: DEFAULT_CURRENT_PAGE }));
  }, [fetchUsers, pagination.pageSize]);

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setPagination({ current: page, pageSize });
  }, []);

  // 删除单个用户
  const handleDeleteUser = useCallback(async (id: number, userName: string) => {
    try {
      setLoading(true);
      await http.delete(`Users/${id}`);
      message.success(`用户 "${userName}" 删除成功！`);
      fetchUsers();
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [fetchUsers]);

  // 批量删除用户 - 使用Modal弹窗确认
  const handleBatchDelete = useCallback(() => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的用户');
      return;
    }

    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          await http.deleteBatch(`Users/DeleteBatch`, selectedRowKeys);
          // 获取选中用户的姓名列表
          const userNames = selectedUsers.map(user => user.userName).join('、');
          message.success(`成功删除 ${userNames} 等 ${selectedRowKeys.length} 个用户！`);
          // 清空选择
          setSelectedRowKeys([]);
          setSelectedUsers([]);
          fetchUsers();
        } catch (error) {
          console.error('批量删除用户失败:', error);
          message.error('批量删除用户失败，请稍后重试');
        } finally {
          setLoading(false);
        }
      },
    });
  }, [selectedRowKeys, selectedUsers, fetchUsers]);


  // 渲染头像 - 使用path字段作为头像路径
  const renderAvatar = (path: string, userName: string) => {
    // 处理头像路径为空的情况
    const avatarSrc = path ? `${imgBaseURL}${path}` : DEFAULT_AVATAR;

    return (
      <Tooltip title={userName}>
        <Avatar
          src={avatarSrc}
          alt={`${userName}的头像`}
          icon={<UserOutlined />} // 图片加载失败时显示的默认图标
        />
      </Tooltip>
    );
  };

  // 显示添加用户弹窗
  const showAddModal = () => {
    setModalTitle('添加用户');
    setCurrentUserId(null);
    setFormInitialValues(undefined);
    setIsModalVisible(true);
  };

  // 显示编辑用户弹窗
  const showEditModal = (record: IUsers) => {
    setModalTitle('修改用户');
    setCurrentUserId(record.userId);
    // 填充表单初始数据
    setFormInitialValues(
      record
     
    );
    setIsModalVisible(true);
  };

  // 表单操作成功后的回调
  const handleFormSuccess = () => {
    // 刷新当前页数据
    fetchUsers();
  };

  //修改用户状态
  const changeUserStatus = useCallback(async (checked: boolean) => {
    confirm({
      title: '确认修改',
      icon: <ExclamationCircleOutlined />,
      content: `确定要${checked?'激活':'冻结'}此用户。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          //await http.deleteBatch(`Users/DeleteBatch`, selectedRowKeys);
          message.success(`用户已成功${checked?'激活':'冻结'}！`);
          //刷新数据
          fetchUsers();
        } catch (error) {
          console.error('修改用户状态失败:', error);
          message.error('修改用户状态失败，请稍后重试');
        } finally {
          setLoading(false);
        }
      },
    });
  },[fetchUsers])


  return (
    <div className="users-container" style={{ padding: '20px' }}>
      <div style={{
        marginBottom: 16,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <Space size="middle">
          <Input
            placeholder="请输入用户名搜索"
            value={searchName}
            onChange={(e) => setSearchName(e.target.value)} // 仅更新状态，不触发搜索
            style={{ width: 300 }}
            allowClear
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            搜索
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 8 }}
            icon={<PlusOutlined />}
            onClick={showAddModal}
          >
            添加用户
          </Button>
        </Space>


        <Button
          danger
          icon={<DeleteOutlined />}
          disabled={selectedRowKeys.length === 0}
          onClick={handleBatchDelete}
        >
          批量删除
        </Button>
      </div>

      <Table<IUsers>
        loading={loading}
        dataSource={users}
        rowKey="userId"
        rowSelection={rowSelection}
        pagination={{
          total: totalCount,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: (total) => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: PAGE_SIZE_OPTIONS,
          position: ['bottomCenter'],
          onChange: handlePaginationChange
        }}
        scroll={{ x: 'max-content' }}
      >
        <Column title="编号" dataIndex="userId" key="userId" width={80} />
        <Column title="头像" dataIndex="path" key="path" width={80} render={(path, record) => renderAvatar(path, record.userName)} />
        <Column title="姓名" dataIndex="userName" key="userName" width={120} />
        <Column title="登录账户" dataIndex="loginName" key="loginName" width={150} />
        <Column title="性别" dataIndex="sex" key="sex" width={80} render={(sex) => (
          <Tag color={sex === '男' ? 'blue' : 'pink'}>
            {sex}
          </Tag>
        )}
        />
        <Column title="出生日期" dataIndex="birthday" key="birthday" width={120} render={(birthday) => (
          <Tooltip title={birthday} placement="top">
            {birthday.substr(0, 10)}
          </Tooltip>
        )} />
        <Column title="手机号码" dataIndex="phone" key="phone" width={140} ellipsis={{ showTitle: false }} render={(phone) => (
          <Tooltip title={phone} placement="top">
            {phone}
          </Tooltip>
        )}
        />
        <ColumnGroup title="角色">
          <Column title="部门" dataIndex="deptName" key="deptName" width={150} />
          <Column title="岗位" dataIndex="roleName" key="roleName" width={150} />
        </ColumnGroup>
        <Column
          title="账户状态"
          dataIndex="status"
          key="status"
          width={80}
          render={(status) => (
            // <Tag color={status === true ? 'green' : 'orange'}>
            //   {status === true ? '正常' : '冻结'}
            // </Tag>
            <Switch checkedChildren="正常" unCheckedChildren="冻结" checked={status} onChange={changeUserStatus} />
          )}
        />
        <Column title="操作" key="action" width={180} render={(_: any, record: IUsers) => (
          <Space size="middle">
            <Button
              type="primary"
              size="small"
              icon={<EditOutlined />}
              onClick={() => showEditModal(record)}
            >
              修改
            </Button>
            <Popconfirm
              title={`确定要删除用户 "${record.userName}" 吗？`}
              onConfirm={() => handleDeleteUser(record.userId, record.userName)}
              okText="确定"
              cancelText="取消"
            >
              <Button danger icon={<DeleteOutlined />} size="small">
                删除
              </Button>
            </Popconfirm>
          </Space>
        )}
        />
      </Table>

      {/* 引入独立的用户表单弹窗组件 */}
      <UserFormModal
        visible={isModalVisible}
        title={modalTitle}
        initialValues={formInitialValues}
        userId={currentUserId}
        loading={!!loading}
        onCancel={() => setIsModalVisible(false)}
        onSuccess={handleFormSuccess}
      />
    </div>
  );
};

export default Users;
